import { Button, Form, Input, message, Select, Upload } from 'antd'
import React, { useEffect, useState } from 'react'
import Layout from '../core/Layout'
import { UploadOutlined } from "@ant-design/icons"
import { useDispatch, useSelector } from 'react-redux'
import { AppState } from '../../store/reducers'
import { CategoryState } from '../../store/reducers/category.reducer'
import { getCategory } from '../../store/actions/category.action'
import { RcFile } from 'antd/lib/upload'
import axios from 'axios'
import { isAuth } from '../../helpers/auth'
import { API } from '../../config'


const AddProduct = () => {
  const dispatch = useDispatch()
  const category = useSelector<AppState,CategoryState>(state=>state.category)
  const [file, setFile] = useState<RcFile>()
  useEffect(()=>{
    console.log('useEffectAddProduct')
    dispatch(getCategory())
    console.log(category)
  },[])
  const props = {
    accept: 'image/*',
    beforeUpload: (file: RcFile) => {
      setFile(file)
      return false
    }
  }
  const onFinish = (product: any) => {
    const {user, token} = isAuth()
    const formData = new FormData()
    for(let attr in product) {
      formData.set(attr, product[attr])
    }
    if(file) {
      formData.set('file', file)
    }
    axios.post(`${API}/product/create/${user._id}`,formData,{
      headers: {
        authorization: `bearer ${token}`
      }
    }).then(()=>{
      message.success('添加成功')
    }).catch(()=>{
      message.error('添加失败')
    })
  }
  return (
    <Layout title="添加商品" subTitle="">
      <Form onFinish={onFinish} initialValues={{category:"",shipping:""}}>
        <Form.Item>
          <Upload {...props}>
            <Button icon={<UploadOutlined />}>上传商品图片</Button>
          </Upload>
        </Form.Item>
        <Form.Item name="name" label="商品名称">
          <Input />
        </Form.Item>
        <Form.Item name="description" label="商品描述">
          <Input />
        </Form.Item>
        <Form.Item name="price" label="商品价格">
          <Input />
        </Form.Item>
        <Form.Item name="category" label="商品分类">
          <Select>
            <Select.Option value="">请选择分类</Select.Option>
            {
              category.category.result.map(item => {
                return <Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item name="quantity" label="商品数量">
          <Input />
        </Form.Item>
        <Form.Item name="shipping" label="商品是否运输">
          <Select>
              <Select.Option value="">请选择商品是否运输</Select.Option>
              <Select.Option value="1">是</Select.Option>
              <Select.Option value="0">否</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">提交</Button>
        </Form.Item>
      </Form>
    </Layout>
  )
}
export default AddProduct